package com.fyb.basic.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁：AtomicReference 实现自旋锁
 */
@SuppressWarnings({"all"})
public class SnipLock {

    // 原子引用线程
    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        // 获得当前线程
        Thread thread = Thread.currentThread();
        // 自选获取
        while (!atomicReference.compareAndSet(null, thread)) {

        }
    }

    public void myUnLock() {
        // 获得当前线程
        Thread thread = Thread.currentThread();
        // 自选获取
        while (!atomicReference.compareAndSet(thread, null)) {

        }
    }

    public static void main(String[] args) throws InterruptedException {
        SnipLock snipLock = new SnipLock();

        new Thread(new Runnable() {
            @Override
            public void run() {
                snipLock.myLock();
                System.out.println(Thread.currentThread().getName() + "开始执行" + "\t");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "释放锁" + "\t");
                snipLock.myUnLock();

            }
        }, "t1").start();
        // 让线程t1 先启动
        TimeUnit.SECONDS.sleep(1);
        System.out.println("====");
        new Thread(new Runnable() {
            @Override
            public void run() {
                snipLock.myLock();
                System.out.println(Thread.currentThread().getName() + "开始执行" + "\t");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "释放锁" + "\t");
                snipLock.myUnLock();
            }
        }, "t2").start();

    }


}
